<template>
  <div class="platform-account">
    <!-- 搜索和操作区 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchKeyword" placeholder="搜索用户名/真实姓名/账号ID" clearable></el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchRole" placeholder="选择角色">
            <el-option label="全部" value=""></el-option>
            <el-option label="平台管理员" value="platform_admin"></el-option>
            <el-option label="学校管理员" value="school_admin"></el-option>
            <el-option label="教师" value="teacher"></el-option>
            <el-option label="家长" value="parent"></el-option>
            <el-option label="学生" value="student"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchStatus" placeholder="选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="active"></el-option>
            <el-option label="禁用" value="inactive"></el-option>
            <el-option label="待激活" value="pending"></el-option>
          </el-select>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="success" @click="handleCreateAccount" style="margin-left: 10px;">
            <el-icon><Plus /></el-icon> 创建账号
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 账号列表 -->
    <el-card class="account-list-card">
      <template #header>
        <span>账号管理</span>
      </template>
      
      <el-table :data="filteredAccounts" border>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="realName" label="真实姓名" width="120"></el-table-column>
        <el-table-column prop="accountId" label="账号ID" width="150"></el-table-column>
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            {{ formatRole(scope.row.role) }}
          </template>
        </el-table-column>
        <el-table-column prop="affiliation" label="所属机构"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="lastLogin" label="最后登录"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 'active' ? 'success' : 
                     scope.row.status === 'pending' ? 'warning' : 'danger'"
            >
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row.id)">详情</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 'active' ? 'danger' : 'success'" 
              @click="handleChangeStatus(scope.row.id, scope.row.status)"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="info" 
              @click="handleResetPassword(scope.row.id, scope.row.username)"
            >
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredAccounts.length"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 重置密码对话框 -->
    <el-dialog 
      title="重置密码" 
      v-model="resetPasswordVisible" 
      width="400px"
    >
      <p>确定要重置 <span class="username-highlight">{{ resetTargetUsername }}</span> 的密码吗？</p>
      <p>重置后，默认密码为：<code>123456</code>，用户需重新登录并修改密码</p>
      <template #footer>
        <el-button @click="resetPasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword">确定重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();

// 搜索条件
const searchKeyword = ref('');
const searchRole = ref('');
const searchStatus = ref('');

// 分页参数
const currentPage = ref(1);
const pageSize = ref(20);

// 账号数据
const accounts = ref([
  {
    id: 1,
    username: 'platformadmin',
    realName: '系统管理员',
    accountId: 'PA20210001',
    role: 'platform_admin',
    affiliation: '平台',
    createTime: '2023-01-01',
    lastLogin: '2023-10-15 09:30',
    status: 'active'
  },
  {
    id: 2,
    username: 'schooladmin1',
    realName: '张明',
    accountId: 'SA20210001',
    role: 'school_admin',
    affiliation: '阳光第一小学',
    createTime: '2023-01-15',
    lastLogin: '2023-10-14 16:45',
    status: 'active'
  },
  {
    id: 3,
    username: 'teacher_zhang',
    realName: '张敏',
    accountId: 'TA20210001',
    role: 'teacher',
    affiliation: '阳光第一小学',
    createTime: '2023-02-20',
    lastLogin: '2023-10-15 10:20',
    status: 'active'
  },
  {
    id: 4,
    username: 'parent_wang',
    realName: '王建国',
    accountId: 'PA20210002',
    role: 'parent',
    affiliation: '阳光第一小学',
    createTime: '2023-03-05',
    lastLogin: '2023-10-13 19:10',
    status: 'active'
  },
  {
    id: 5,
    username: 'student123',
    realName: '王小明',
    accountId: 'ST20210001',
    role: 'student',
    affiliation: '阳光第一小学',
    createTime: '2023-03-10',
    lastLogin: '2023-10-15 14:30',
    status: 'active'
  },
  {
    id: 6,
    username: 'teacher_li',
    realName: '李强',
    accountId: 'TA20210002',
    role: 'teacher',
    affiliation: '希望中学',
    createTime: '2023-02-25',
    lastLogin: '2023-09-30 11:20',
    status: 'inactive'
  },
  {
    id: 7,
    username: 'schooladmin2',
    realName: '赵伟',
    accountId: 'SA20210002',
    role: 'school_admin',
    affiliation: '蓝天实验小学',
    createTime: '2023-10-10',
    lastLogin: '',
    status: 'pending'
  }
]);

// 筛选账号
const filteredAccounts = computed(() => {
  return accounts.value.filter(account => {
    const keywordMatch = !searchKeyword.value || 
      account.username.includes(searchKeyword.value) || 
      account.realName.includes(searchKeyword.value) ||
      account.accountId.includes(searchKeyword.value);
    const roleMatch = !searchRole.value || account.role === searchRole.value;
    const statusMatch = !searchStatus.value || account.status === searchStatus.value;
    return keywordMatch && roleMatch && statusMatch;
  });
});

// 状态统计
const activeCount = computed(() => {
  return accounts.value.filter(a => a.status === 'active').length;
});

const inactiveCount = computed(() => {
  return accounts.value.filter(a => a.status === 'inactive').length;
});

const pendingCount = computed(() => {
  return accounts.value.filter(a => a.status === 'pending').length;
});

// 格式化角色显示
const formatRole = (role) => {
  const roleMap = {
    platform_admin: '平台管理员',
    school_admin: '学校管理员',
    teacher: '教师',
    parent: '家长',
    student: '学生'
  };
  return roleMap[role] || role;
};

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    active: '正常',
    inactive: '禁用',
    pending: '待激活'
  };
  return statusMap[status] || status;
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  console.log('搜索账号:', { 
    keyword: searchKeyword.value, 
    role: searchRole.value, 
    status: searchStatus.value 
  });
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 查看详情
const handleViewDetail = (id) => {
  router.push(`/platform/account/detail/${id}`);
};

// 编辑账号
const handleEdit = (id) => {
  router.push(`/platform/account/edit/${id}`);
};

// 更改状态（启用/禁用）
const handleChangeStatus = (id, currentStatus) => {
  const action = currentStatus === 'active' ? '禁用' : '启用';
  ElConfirm(`确定要${action}该账号吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const account = accounts.value.find(a => a.id === id);
    if (account) {
      account.status = currentStatus === 'active' ? 'inactive' : 'active';
      ElMessage.success(`${action}成功`);
    }
  });
};

// 创建账号
const handleCreateAccount = () => {
  router.push('/platform/account/create');
};

// 重置密码相关
const resetPasswordVisible = ref(false);
const resetTargetId = ref(null);
const resetTargetUsername = ref('');

const handleResetPassword = (id, username) => {
  resetTargetId.value = id;
  resetTargetUsername.value = username;
  resetPasswordVisible.value = true;
};

const confirmResetPassword = () => {
  // 实际项目中调用密码重置接口
  ElMessage.success(`已重置 ${resetTargetUsername.value} 的密码`);
  resetPasswordVisible.value = false;
};
</script>

<style scoped>
.platform-account {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  padding: 15px;
}

.account-list-card {
  padding: 15px;
}

.status-stats {
  display: flex;
  align-items: center;
}

.status-badge {
  margin-left: 10px;
}

.total-count {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.username-highlight {
  color: #1890ff;
  font-weight: bold;
}
</style>
